package com.hxf.web.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证码
 * @author tengyicheng
 *
 */
public class ValidatecodeAction extends WebActionBase {

	static{
        System.setProperty("java.awt.headless", "true");
    }
	
	public String index() {

		int width = 60;
		int height = 20;
		HttpServletResponse response = super.getResponse();
		BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

		Graphics g = buffImg.createGraphics();
		// Graphics2D g2d=(Graphics2D)g;

		Random random = new Random();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, width, height);
		Font font = new Font("Times New Roman", Font.PLAIN, 18);
		g.setFont(font);
		g.setColor(Color.GRAY);
		g.fillRect(0, 0, width - 1, height - 1);

		g.setColor(Color.pink);

		for (int i = 0; i < 200; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int x1 = random.nextInt(12);
			int y1 = random.nextInt(12);
			g.drawLine(x, y, x1, y1);
		}

		StringBuffer randomCode = new StringBuffer();
		int red = 0, green = 0, blue = 0;
		for (int i = 0; i < 4; i++) {
			String strRand = String.valueOf(random.nextInt(10));
			red = random.nextInt(110);
			green = random.nextInt(90);
			blue = random.nextInt(50);

			g.setColor(new Color(red, green, blue));
			g.drawString(strRand, 13 * i + 6, 16);
			randomCode.append(strRand);
		}
		
		getSession().setAttribute("validateCode", randomCode.toString());
		
		g.dispose();
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setDateHeader("Expires", 0);
		// 生成图片
		response.setContentType("image/jpeg");

		try {
			ImageIO.write(buffImg, "JPEG", response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
}
